package cn.lyjuan.archetypes.bms.web.config;

import cn.lyjuan.archetypes.bms.common.entity.MgManage;
import cn.lyjuan.archetypes.bms.web.service.ActionService;
import cn.lyjuan.archetypes.bms.web.service.ManageService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chad on 2016/8/23.
 * 为独立SQL代码，启用该服务
 */
public class UserDetailsServiceImpl implements UserDetailsService
{
    private ManageService manageService;

    private ActionService actionService;

    public UserDetailsServiceImpl(ManageService manageService, ActionService actionService)
    {
        this.manageService = manageService;
        this.actionService = actionService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        // 查找用户
        MgManage user = manageService.queryManageByName(username);
        if (null == user)
            throw new UsernameNotFoundException(username + " not found");

        // 权限
        List<GrantedAuthority> auths = null;

        // 岗位权限
        List<String> ctls = actionService.queryAllActions(user.getId());

        auths = new ArrayList<>(ctls.size());
        for (String c : ctls)
            auths.add(new SimpleGrantedAuthority(c));

        return new AppUserDetail(user, auths);
    }
}
